package com.itheima.web.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //获取请求头token，如果没有返回401
        String token = request.getHeader("Authorization");
        token = token.replaceAll("Bearer ", "");

        if (StrUtil.isEmpty(token)) {
            response.setStatus(401);
            return false;
        }

        //如果有token，去Redis中查询是否在有效期
        if (!stringRedisTemplate.hasKey(ConstantUtil.ADMIN_TOKEN + token)) {
            response.setStatus(401);
            return false;
        }

        //解析token，失败401，成功将user信息存入th，并给token续期
        try {
            Map map = JwtUtil.parseToken(token);
            Admin admin = BeanUtil.mapToBean(map, Admin.class, true);

            //成功
            //1.将user存入th
            AdminHolder.set(admin);

            //2.给token续期
            stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, admin.getId() + ":" + admin.getUsername(), Duration.ofHours(1));

            //放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    //页面渲染完成后，移除th
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        AdminHolder.remove();
    }
}
